package com.hd.util.lucene;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class LuceneUtil {
	// 索引存放位置
	public static final String STORE_INDEX_PATH = "D:\\hzhh123\\index";
	public static final String STORE_FILE_PATH = "D:\\hzhh123\\file";
	
	public static void index(){
		IndexWriter writer = null;
		int numIndexed=0;
		long start=System.currentTimeMillis();
		try {
			// 1、创建Derictory
			// 建立在内存中的索引
			// Directory directory=new RAMDirectory();
			// 这个方法是建立在磁盘上面的索引
			Directory directory = FSDirectory.open(Paths.get(STORE_INDEX_PATH));
			// 2、创建IndexWriter，用完后要关闭
			Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
			IndexWriterConfig config = new IndexWriterConfig(analyzer);
			writer = new IndexWriter(directory, config);
			// 3、创建Document对象
			Document document = null;
			File files = new File(STORE_FILE_PATH);
			// 4、为Document添加Field
			for (File file : files.listFiles()) {
				System.out.println(file.getName());
				document = new Document();
				document.add(new TextField("contents", new FileReader(file)));
				// 把文件名存放到硬盘中，不作分词
				document.add(new TextField("fileName", file.getName(), Field.Store.YES));
				// 把绝对路径放到硬盘中，不作分词
				document.add(new TextField("path", file.getAbsolutePath(), Field.Store.YES));
				writer.addDocument(document);
			}
			numIndexed=writer.numDocs();
			// 5、通过IndexWriter添加文档到索引中
			long end=System.currentTimeMillis();
			System.out.println("索引："+numIndexed+" 个文件 花费了"+(end-start)+" 毫秒");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
     * 搜索
     */
    public static void searcher(String q){
    	IndexReader reader=null;
        try {
            //1、创建Directory
            Directory directory = FSDirectory.open(Paths.get(STORE_INDEX_PATH));

            //2、创建IndexReader，需要关闭
            reader = DirectoryReader.open(directory);

            //3、根据IndexReader创建IndexSearcher
            IndexSearcher searcher = new IndexSearcher(reader);
            Analyzer analyzer=new StandardAnalyzer(); // 标准分词器

            //4、创建索引的Query
            //第二个参数代表着要搜索的域
            QueryParser parser=new QueryParser("contents", analyzer);
            //表示搜索content中包含java的文档
            Query query = parser.parse(q);
            //5、根据searcher搜索并返回TopDocs
//            表示返回前面10条
            long start=System.currentTimeMillis();
    		TopDocs topDocs=searcher.search(query, 10);
    		long end=System.currentTimeMillis();
    		System.out.println("匹配 "+q+" ，总共花费"+(end-start)+"毫秒"+"查询到"+topDocs.totalHits+"个记录");
            //6、根据TopDocs获取ScoreDoc对象
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for(ScoreDoc sd : scoreDocs){
                //7、根据Searcher和ScordDoc对象获取具体的Document对象
                //获取这个文档的id
                int doc = sd.doc;
                Document document = searcher.doc(doc);
                //8、根据Document对象获取需要的值
                System.out.println("【找到】" + document.get("fileName") + "    " + document.get("path"));
            }
           
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(reader!=null){
				 try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

    }
	public static void main(String[] args) {
		//index();
		String q="Lucene 5.3.0";
		searcher(q);
	}
}
